package com.leyou.user.controller;

import com.leyou.common.exceptions.LyException;
import com.leyou.user.entity.User;
import com.leyou.user.entity.UserDTO;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkUsernameAndPhone(@PathVariable("data") String data,
                                                         @PathVariable("type") Integer type){
        return ResponseEntity.ok(userService.checkUsernameAndPhone(data,type));
    }

    @PostMapping("/code")
    public ResponseEntity<Void> sendCheckCode(@RequestParam("phone") String phone){
        userService.sendCheckCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid User user,
                                         BindingResult result,
                                         @RequestParam("code") String code,
                                         @RequestParam("confirmPassword") String confirmPassword){
        if(result.hasErrors()){
            String errorMsgs = result.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining("/"));
            throw new LyException(400,errorMsgs);
        }
        userService.register(user,code,confirmPassword);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @GetMapping("/query")   //登录时从前端传来username和password 然后后端接收参数用来跟数据库中的数据进行比对
    public ResponseEntity<UserDTO> findByUsernameAndPassword(@RequestParam("username") String username,
                                                             @RequestParam("password") String password){
        return ResponseEntity.ok(userService.findByUsernameAndPassword(username, password));
    }
}
